/**
 * Created by chocolate on 16/5/27.
 */
'use strict';

import React, {
  Component,
} from 'react';
import {
  Linking,
  Platform,
  ActionSheetIOS,
  Dimensions,
  View,
  Text,
  Navigator,
} from 'react-native';
var GiftedMessenger = require('react-native-gifted-messenger');
var Communications = require('react-native-communications');
var chatQuery = require('./Query').query;
//var chatQuery = new Query();
var Title = require('./Title');

var STATUS_BAR_HEIGHT = Navigator.NavigationBar.Styles.General.StatusBarHeight;
// if (Platform.OS === 'android') {
//   var ExtraDimensions = require('react-native-extra-dimensions-android');
//   var STATUS_BAR_HEIGHT = ExtraDimensions.get('STATUS_BAR_HEIGHT');
// }

class ChatScreen extends Component {

  constructor(props) {
    super(props);
    this.startQueryDate = "0000-00-00 00:00:00";
    this.myside = this.props.myside;
    this.yourside = this.props.yourside;
    this.timerCount = 3300;
    this.firstQuery = true;
    this._isMounted = false;
    this._messages = this.getInitialMessages();
    this.state = {
      messages: this._messages,
      isLoadingEarlierMessages: false,
      typingMessage: '',
      allLoaded: false,
      avatarSource:g_avatar,
    };
  }
  componentDidMount() {

    this._isMounted = true;

    //单聊消息，只从服务器读取未“看见”的消息
    if(this.props.group === false){
      this.getNewTimer = setInterval(() =>{
                    //从网络查询最新未读消息
                    chatQuery.readChatLatestNewMsg(
                      this.myside,
                      this.yourside,
                      this,
                      function(owner,response){
                        if(response.success === true){
                          console.log("从服务器成功收到最新未读消息"+response.message);
                          owner.handleReceive(response.message); 
                          owner.firstQuery = false;
                        }});
                    },this.timerCount);
      }

      //群聊消息，从服务器读取最近n条消息，不管是否看见（群聊本地不保存）
      else{

        this.getNewTimer = setInterval(() =>{
                  //从网络查询最新未读消息
                  chatQuery.readChatLatestGroupMsg(
                      this.myside,
                      this.yourside,
                      this.startQueryDate,
                      10,
                      this,
                      function(owner,response){
                        if(response.success === true){
                          console.log("从服务器收到最新100条群聊消息"+response.message);
                          owner.handleReceive(response.message); 
                          owner.firstQuery = false;
                        }});
                 },this.timerCount);
      }
  }


  componentWillUnmount() {
    this._isMounted = false;
    //结束时必须清空定时器，否则它会一直在运行
    this.getNewTimer && clearTimeout(this.getNewTimer);

    //只有单聊才在本地存储历史消息
    if(this.props.group === false){
       storage.save({
          key: 'chat',  //注意:请不要在key中使用_下划线符号!
          id:this.props.yourside,
          rawData: this.state.messages,
          expires: null
        });
    }
  }

  getInitialMessages() {
    return [];
  }

  setMessageStatus(uniqueId, status) {
    let messages = [];
    let found = false;

    for (let i = 0; i < this._messages.length; i++) {
      if (this._messages[i].uniqueId === uniqueId) {
        let clone = Object.assign({}, this._messages[i]);
        clone.status = status;
        messages.push(clone);
        found = true;
      } else {
        messages.push(this._messages[i]);
      }
    }

    if (found === true) {
      this.setMessages(messages);
    }
  }

  setMessages(messages) {
    this._messages = messages;

    // append the message
    this.setState({
      messages: messages,
    });
  }

  handleSend(message = {}) {

    // Your logic here
    // Send message.text to your server
    chatQuery.sendChatMsg(this.myside,
                          this.yourside,
                          message.text,
                          // this.startQueryDate = new Date().Format("yyyy-MM-dd hh:mm:ss"),
                          new Date().Format("yyyy-MM-dd hh:mm:ss"),
                          this,
                          function(owner,response){
                            if(response.success === true){
                              console.log("成功发送消息到服务器");
                            }});

    message.uniqueId = Math.round(Math.random() * 10000); // simulating server-side unique id generation
    this.setMessages(this._messages.concat(message));

    // mark the sent message as Seen
    setTimeout(() => {
      this.setMessageStatus(message.uniqueId, 'Seen'); // here you can replace 'Seen' by any string you want
    }, 1000);

   

    // if you couldn't send the message to your server :
    // this.setMessageStatus(message.uniqueId, 'ErrorButton');
  }

  onLoadEarlierMessages() {

    // display a loader until you retrieve the messages from your server
    this.setState({
      isLoadingEarlierMessages: true,
    });

    // IMPORTANT
    // Oldest messages have to be at the begining of the array
    var earlierMessages = [];

    if(this.props.group === false){
      storage.load({
        key: 'chat',
        id:this.props.yourside,
        autoSync: true,
        syncInBackground: true
      }).then(ret => {
        earlierMessages = ret;
        this.setMessages(earlierMessages.concat(this._messages)); // prepend the earlier messages to your list
        this.setState({
          isLoadingEarlierMessages: false, // hide the loader
          allLoaded: true, // hide the `Load earlier messages` button
        });
      }).catch(err => {
        console.log('本地无聊天记录');
      })
    }
  }

  handleReceive(message = {}) {
    if(this.props.group === false){
      message.forEach((item, index, array)=>{
        item.image = {uri:this.props.yourPicture};  //从ChatList传入一次即可
      })
    }
    else{
      if(message.length !== 0){
        this.startQueryDate = message[0].dateStr; 
      }

      var tmpMessage = [];
      //删除本人发送的群组消息
      for(var i = message.length-1;i >= 0;i--){
        if(this.firstQuery === true || (this.firstQuery === false && message[i].position !== "right")){
          tmpMessage.push(message[i])
        }
      }
      message = tmpMessage;
      message.forEach((item, index, array)=>{
        item.image = {uri:item.image};  //必须从服务器获取，因为
      })

    }
    this.setMessages(this._messages.concat(message));

  }

  onErrorButtonPress(message = {}) {
    // Your logic here
    // re-send the failed message

    // remove the status
    this.setMessageStatus(message.uniqueId, '');
  }

  // will be triggered when the Image of a row is touched
  onImagePress(message = {}) {
    // Your logic here
    // Eg: Navigate to the user profile
  }

  /**
   * 点击Title"返回"按钮的响应函数
   * @private
   */
  _onPressReturn(){
    this.props.navigator.pop();
  }

  render() {
    return (
      <View>
        <Title title={{left:"返回",center:("聊天"),leftAct:this._onPressReturn.bind(this)}}></Title>
        <GiftedMessenger
          ref={(c) => this._GiftedMessenger = c}

          styles={{
            bubbleRight: {
              marginLeft: 70,
              backgroundColor: '#2981b1',
            },

          }}

          autoFocus={false}
          messages={this.state.messages}
          handleSend={this.handleSend.bind(this)}
          onErrorButtonPress={this.onErrorButtonPress.bind(this)}
          maxHeight={Dimensions.get('window').height - Navigator.NavigationBar.Styles.General.NavBarHeight - STATUS_BAR_HEIGHT}

          loadEarlierMessagesButton={!this.state.allLoaded}
          onLoadEarlierMessages={this.onLoadEarlierMessages.bind(this)}

          senderName='Awesome Developer'
          senderImage={this.state.avatarSource}
          onImagePress={this.onImagePress}
          displayNames={true}

          parseText={true} // enable handlePhonePress, handleUrlPress and handleEmailPress
          handlePhonePress={this.handlePhonePress}
          handleUrlPress={this.handleUrlPress}
          handleEmailPress={this.handleEmailPress}

          keyboardShouldPersistTaps={false}
          sendButtonText={'发送'}
          placeholder={'请输入消息...'}
          isLoadingEarlierMessages={this.state.isLoadingEarlierMessages}
          loadEarlierMessagesButtonText={'加载早前的消息'}
          typingMessage={this.state.typingMessage}
          submitOnReturn={true}
        />
      </View>
    );
  }

  handleUrlPress(url) {
    Linking.openURL(url);
  }

  // TODO
  // make this compatible with Android
  handlePhonePress(phone) {
    if (Platform.OS !== 'android') {
      var BUTTONS = [
        'Text message',
        'Call',
        'Cancel',
      ];
      var CANCEL_INDEX = 2;

      ActionSheetIOS.showActionSheetWithOptions({
          options: BUTTONS,
          cancelButtonIndex: CANCEL_INDEX
        },
        (buttonIndex) => {
          switch (buttonIndex) {
            case 0:
              Communications.phonecall(phone, true);
              break;
            case 1:
              Communications.text(phone);
              break;
          }
        });
    }
  }

  handleEmailPress(email) {
    Communications.email(email, null, null, null, null);
  }

}


module.exports = ChatScreen;